import sys
 
from PyQt4.Qt import Qt, QObject, QApplication, QLineEdit, QCompleter,QDialog,  QStringListModel, SIGNAL
from PyQt4 import QtCore
from PyQt4.QtGui import QValidator
from KDataBase.KQueryDB import KQueryDB

class _KStockComplter(QCompleter):
 
    def __init__(self, parent, all_tags):
        QCompleter.__init__(self, all_tags, parent)
        self.all_tags = set(all_tags)
 
    def update(self, text_tags, completion_prefix):
        tags = list(self.all_tags.difference(text_tags))
        model = QStringListModel(tags, self)
        self.setModel(model)
 
        self.setCompletionPrefix(completion_prefix)
        if completion_prefix.strip() != '':
            self.complete()
            
      
        
        
class KChartCompleteEdit(QLineEdit):
    
    AllSymbols=KQueryDB.QueryAllStockNames()
    SymbolObtained=QtCore.pyqtSignal(str)
    def __init__(self, *args):
        QLineEdit.__init__(self, *args)
 
        QObject.connect(self, SIGNAL('textChanged(QString)'), self.text_changed)

        self.completer = _KStockComplter(self, self.AllSymbols)
        completer=self.completer
        completer.setCaseSensitivity(Qt.CaseInsensitive)         
        QObject.connect(self,SIGNAL('text_changed(PyQt_PyObject, PyQt_PyObject)'), completer.update)        
        QObject.connect(completer, SIGNAL('activated(QString)'),  self.complete_text)     
        completer.setWidget(self) 
        
        self.returnPressed.connect(self.OnReturnPressed)
    def IsTextValid(self,text):
        if text in KChartCompleteEdit.AllSymbols:
            return True
        else:
            return False
    
    def OnReturnPressed(self):
        if self.IsTextValid(self.text()):
            self.SymbolObtained.emit(self.text())   
        
    def text_changed(self, text):
        all_text = unicode(text)
        text = all_text[:self.cursorPosition()]
        prefix = text.split(',')[-1].strip()
 
        text_tags = []
        for t in all_text.split(','):
            t1 = unicode(t).strip()
            if t1 != '':
                text_tags.append(t)
        text_tags = list(set(text_tags))
 
        self.emit(SIGNAL('text_changed(PyQt_PyObject, PyQt_PyObject)'),
            text_tags, prefix)
 
    def complete_text(self, text):
        self.setText(text)
        if self.IsTextValid(self.text()):
            self.SymbolObtained.emit(self.text())            

